import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_vant_kit/widgets/actionSheet.dart';
import 'package:flutter_vant_kit/widgets/cell.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:shoes_shop/api/api.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shoes_shop/core/utils.dart';
import 'package:shoes_shop/models/public_provider_model.dart';

import 'addressList/address_list_page.dart';
import 'inputText/input_text_page.dart';

class UpdataUserInfoPage extends StatelessWidget {
  const UpdataUserInfoPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<ActionSheetItem> actionList = [
      ActionSheetItem(name: "男"),
      ActionSheetItem(name: "女"),
    ];
    return Scaffold(
        appBar: AppBar(
          leading: BackButton(),
          title: Text('我的信息'),
          // backgroundColor: AppColors.purplishBlue,
        ),
        body: Consumer<PublicProviderModel>(
          builder: (context, provide, child) => Column(
            children: [
              SizedBox(height: 20.w),
              Cell(
                  title: "头像",
                  // value: "选择头像",
                  clickable: true,
                  customRight: CircleAvatar(
                    backgroundColor: Colors.grey,
                    //头像半径
                    radius: 30,
                    //头像图片
                    backgroundImage: provide.userInfo['avatarUrl'] == null
                        ? AssetImage('assets/astronaut.png')
                        : NetworkImage(provide.userInfo['avatarUrl']),
                  ),
                  onClick: () async {
                    String avatarUrl = await changeAvatar();
                    Provider.of<PublicProviderModel>(context,
                            listen: false).changeUserInfoValue('avatarUrl', avatarUrl);
                    Map userInfo = Provider.of<PublicProviderModel>(context,
                            listen: false)
                        .userInfo;
                    Map res = await updateUserInfo(userInfo);
                    showToast(res['message']);
                  }),
              Cell(
                  title: "昵称",
                  value: provide.userInfo['nickname'] ?? provide.userInfo['email'],
                  isLink: true,
                  onClick: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => InputTextPage(
                            nickname: provide.userInfo['nickname']),
                      ),
                    );
                  }),
              Cell(
                title: "性别",
                value: provide.userInfo['gender'] == -1
                    ? '请选择'
                    : actionList[provide.userInfo['gender']].name,
                isLink: true,
                onClick: () {
                  ActionSheet(
                      actions: actionList,
                      cancelText: '取消',
                      onSelect: (ActionSheetItem actionSheetItem, int index,
                              BuildContext context)
                          async {
                            Provider.of<PublicProviderModel>(context,
                            listen: false).changeUserInfoValue('gender', index);
                            Map userInfo = Provider.of<PublicProviderModel>(context,
                            listen: false).userInfo;
                            Map res = await updateUserInfo(userInfo);
                            showToast(res['message']);
                          }).show(context);
                },
              ),
              Cell(
                title: "管理我的地址",
                // value: "请选择选择地址",
                isLink: true,
                onClick: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => AddressListPage(),
                    ),
                  );
                },
              ),
            ],
          ),
        ));
  }

  // 修改头像 获取并裁剪图片 上传图片
  Future changeAvatar() async {
    // ImageSource.gallery 访问本地图库
    // ImageSource.camera 访问相机
    var image = await ImagePicker().getImage(source: ImageSource.gallery);
    print('图片地址：$image');
    if (image != null) {
      // 这里调用第二个剪切组件
      File croppedFile = await ImageCropper().cropImage(
          sourcePath: image.path,
          // ratioX: 1.0,
          // ratioY: 1.0,
          maxWidth: 512,
          maxHeight: 512,
          androidUiSettings: AndroidUiSettings(
              hideBottomControls: true,
              initAspectRatio: CropAspectRatioPreset.square,
              lockAspectRatio: true),
          iosUiSettings: IOSUiSettings(
            minimumAspectRatio: 1.0,
          ));
      print('裁剪后的图片$croppedFile');
      if (croppedFile.path != null) {
        DateTime today = new DateTime.now();
        String nowString =
            "${today.year.toString()}${today.month.toString().padLeft(2, '0')}${today.day.toString().padLeft(2, '0')}${today.hour.toString()}${today.minute.toString()}${today.microsecond.toString()}";
        print(nowString);
        String imgUrl =
            await uploadFile('img/avatar/$nowString.png', croppedFile.path);
        return imgUrl;
      }
    }
  }
}
